package com.wyg.ep_timer.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.wyg.epcommonbase.common.util.BeanMapper;
import com.wyg.epcommonbase.common.util.StringUtil;
import com.wyg.ep_timer.entity.Article;
import com.wyg.ep_timer.entity.CompanyNum;
import com.wyg.ep_timer.entity.DataResult;
import com.wyg.ep_timer.feign.HttpUtil;
import com.wyg.ep_timer.mapper.*;
import com.wyg.ep_timer.service.ArticleEntityService;
import com.wyg.ep_timer.service.ArticleKwService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: WangYongGan
 * @Date: 2021/11/1 16:18
 * @Description:
 */
@Configuration
@Slf4j
@EnableScheduling
public class DealDataTask {
    //远程调用

    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    DataResultMapper dataResultMapper;
    @Autowired
    CompanyNumMapper companyNumMapper;
    @Autowired
    ArticleKwService articleKwService;
    @Autowired
    ArticleEntityService articleEntityService;
    @Autowired
    ArticleEntityMapper articleEntityMapper;
    @Autowired
    ArticleKwMapper articleKwMapper;

    //任务2：处理数据
    @Scheduled(cron = "0 0/10 * * * ?")
    public void dealData() {
        log.warn("begin");
        dealData(300);//10min最多处理300条
    }

    public int dealData(int n) {
//        LockSupport.park();
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        List<Article> notDealDataSet = articleMapper.selectList(wrapper.eq("is_deal", false).eq("is_valid", true).last("limit " + n));
        n = Math.min(notDealDataSet.size(), n);
        if (n > 0) {
            log.error("处理" + n + "条数据");
            dealData(notDealDataSet.subList(0, n));
            log.warn("处理完毕::" + notDealDataSet.size());
        } else log.error("没有数据，暂停10分钟");
        return n;
    }


    //    public void dealDataQuick(int n){
//        QueryWrapper<DataResult> wrapper = new QueryWrapper<>();
//        //一次处理1000条
//        for(int k=0;k<n;k+=1000){
//
//            List<DataResult>list=dataResultMapper.selectList(wrapper.last("limit "+k+","+(k+1000)));
//            for (DataResult dataResult : list) {
//                if(!ContantString.flagTemp)
//                    return;
//                //处理dataResult.articleId
//                Article article = articleMapper.selectOne(new QueryWrapper<Article>().eq("scheme", dataResult.getScheme()));
//                dataResult.setArticleId(article.getId());
//                dataResultMapper.updateById(dataResult);
//                //处理article-entity
//                String[] entities = dataResult.getEntity().split(";");
//                String[]regEntities=dataResult.getRegEntity().split(";");
//                ArticleEntity articleEntity=new ArticleEntity();
//                articleEntity.setArticleId(dataResult.getArticleId());
//                articleEntity.setIsReg(dataResult.isReg);
//                for (String entity : entities) {
//                    if(!StringUtils.isEmpty(entity)){
//                        System.out.println(entity);
//                        articleEntity.setEntity(entity);
//                        articleEntityMapper.insert(articleEntity);
//                        //处理company-num
//                        CompanyNum companyNum = Optional.ofNullable(companyNumMapper.selectOne(new QueryWrapper<CompanyNum>().eq("name", entity))).orElse(new CompanyNum());
//                        companyNum.setName(entity);
//                        companyNum.setAllNum(companyNum.getAllNum()+1);
//                        if(dataResult.isReg)
//                            companyNum.setRegNum(companyNum.getRegNum()+1);
//                    }
//                }
//                //处理article-kw
//                //获得关键字
//                WordsResp wordsResp = (WordsResp) HttpUtil.sendGet(Constant.urlGetWords, null);
//                wordsResp.getWords().forEach(word -> {
//                    ArticleKw articleKw = new ArticleKw();
//                    articleKw.setArticleId(dataResult.getArticleId());
//                    articleKw.setKeyword(word);
//                    articleKwMapper.insert(articleKw);
//                });
//            }
//        }
//
//    }
//
    private void dealData(List<Article> dataSet) {
        for (Article data : dataSet) {
            articleMapper.updateDeal(data.getId());
            //文本长度小于10 不合理
            if (data.getRawText().length() < 20) {
                articleMapper.updateValid(data.getId());
                continue;
            }
            log.info("处理id:" + data.getId() + "\ttext:" + data.getRawText().substring(0, 20));
            //标记已经处理
            try {
                final List<String> entities = deal(data);
                synchronized (Resource.lock) {
                    for (String entity : entities) {
                        Integer num = (Integer) Resource.cache.get(entity);
                        num = num == null ? 0 : num;
                        Resource.cache.set(entity, num + 1);
                    }
                }
            } catch (Exception e) {
                articleMapper.updateValid(data.getId());
            }
        }
    }

    private List<String> deal(Article data) {
        //关键字
//        articleKwService.saveArticleKeyWord(data);
        String title = data.getTitle().equals("None") ? "" : data.getTitle() + ",";
        data.setTitle(title);
        List<String> regEntities = new ArrayList<>();
        List<String> entities = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        DataResult dataResult = BeanMapper.copyByClass(data, DataResult.class);
        try {
            jsonObject.put("text", data.getTitle() + data.getRawText());
            //获得entity
            entities = HttpUtil.sendPostGetEntities(jsonObject);
            //对没给entity分析情感 得到reg_entities
            for (String i : entities) {
                jsonObject.put("entity", i);
                if (HttpUtil.setPostEmotionOfEntity(jsonObject)) {
                    dataResult.setIsReg(1);
                    regEntities.add(jsonObject.getString("entity"));
                }
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
        //更新Article 插入result

        dataResult.setEntity(StringUtil.trimList(entities));
        dataResult.setRegEntity(StringUtil.trimList(regEntities));
        //更新entityAll
        entities.forEach(entity -> {
//            if (entity.equals("") || entity.equals(" ")) {
//                errorLogService.insert(2, "entity为空", "entity为空");
//                log.error("wyg::::" + data.getId());
//            }
            updateEntity(entity, false);
//            articleEntityService.saveArticleEntity(data, entity, regEntities.contains(entity));
        });
        regEntities.forEach(entity -> {
            updateEntity(entity, true);
        });
        dataResult.setArticleId(data.getId());
        dataResult.setId(null);
        dataResultMapper.insert(dataResult);
        return entities;
    }

    /**
     * @Description:
     * @Params: mapper, entity, 实例
     * @return:
     **/
    @SneakyThrows
    private void updateEntity(String entity, boolean reg) {
        CompanyNum company = companyNumMapper.selectOne(new QueryWrapper<CompanyNum>().eq("name", entity));
        if (company == null) {
            companyNumMapper.insert(new CompanyNum(entity, 1));
        } else {
            if (reg)
                company.setRegNum(company.getRegNum() + 1);
            else company.setAllNum(company.getAllNum() + 1);
            companyNumMapper.update(company, new QueryWrapper<CompanyNum>().eq("name", entity));
        }
    }

}
